package m2team.com.zuatet.game;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;
import android.widget.ViewFlipper;
import java.util.ArrayList;
import java.util.Random;

import m2team.com.zuatet.Common;
import m2team.com.zuatet.MyLog;
import m2team.com.zuatet.R;

public class MemoryActivity extends Activity implements OnItemClickListener {
	GridView gridViewAnswer;
	ImageView imgView;
	TextView memoryText;
	TextView question_text;
	ArrayList<Integer> ansList = new ArrayList<Integer>();
	int numberOfChallenger = 4;
	int alarmId = 0;
	int currentIndex = 0;
	int numberOfPlay = 0;
	final int FLIP_INTERVAL = 2000;
	final int FLIP_SOCIAL_INTERVAL = 1000;
	CustomGridMemoryAdapter adapter = null;
	String memoryAnswer = "";
	String memoryChoice = "";
	int timeToDelay = 500;
	Handler handler;
	Runnable waitStartRunnable, repeatRunnable;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_memory);
		memoryText = (TextView) findViewById(R.id.memory_text);
		question_text = (TextView) findViewById(R.id.question_text);
		gridViewAnswer = (GridView) findViewById(R.id.memory_grid_answer);
		imgView = (ImageView) findViewById(R.id.imgViewIcon);
		playGame();
		adapter = new CustomGridMemoryAdapter(MemoryActivity.this, ansList,
				1);
		gridViewAnswer.setAdapter(adapter);
		gridViewAnswer.setOnItemClickListener(MemoryActivity.this);
		memoryText.setText("Remember the order");
		Blink();
	}

	private void playGame() {
		memoryAnswer = "";
		// memory social's icon game
		generateRandomIcon(numberOfChallenger, arrSocialIcon1.length - 1);
		memorySocialIcon(numberOfChallenger);
	}

	public static int[] arrSocialIcon1 = { R.drawable.facebook,
			R.drawable.flickr, R.drawable.myspace, R.drawable.twitter };

	/**
	 * generate number of random icon
	 * 
	 * @param size
	 *            : number of icon
	 */
	private void generateRandomIcon(int size, int max) {
		ansList.clear();
		Random random = new Random();
		for (int i = 0; i < size; i++) {
			int choice = random.nextInt(max);
			while (ansList.contains(choice)) {
				choice = random.nextInt(max);
			}
			ansList.add(choice);
		}
		MyLog.d("generate list: " + ansList);
	}

	/**
	 * generate social icon to add to imageView
	 * 
	 * @param size
	 */
	private void memorySocialIcon(int size) {
		question_text.setVisibility(View.INVISIBLE);
		gridViewAnswer.setVisibility(View.INVISIBLE);
		imgView.setVisibility(View.INVISIBLE);
		final AnimationDrawable anim = new AnimationDrawable();
		BitmapDrawable frame1;
		for (int i = 0; i < size; i++) {
			memoryAnswer += ansList.get(i) + Common.COMMA_TOKEN;
			frame1 = (BitmapDrawable) getResources().getDrawable(
					arrSocialIcon1[ansList.get(i)]);
			anim.addFrame(frame1, FLIP_SOCIAL_INTERVAL);
		}
		anim.setOneShot(false);
		imgView.setBackgroundDrawable(anim);
		// run animation after 2s
		final Handler handler = new Handler();
		handler.postDelayed(new Runnable() {
			public void run() {
				imgView.setVisibility(View.VISIBLE);
				anim.start();
			}
		}, FLIP_INTERVAL);
		// hide animation and show choice list
		handler.postDelayed(new Runnable() {
			public void run() {
				anim.stop();
				gridViewAnswer.setVisibility(View.VISIBLE);
				imgView.setVisibility(View.INVISIBLE);
				question_text.setVisibility(View.VISIBLE);
			}
		}, FLIP_SOCIAL_INTERVAL * size + FLIP_INTERVAL);

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		view.setBackgroundColor(getResources().getColor(R.color.gray_100));
		currentIndex++;
		memoryChoice += adapter.getItem(position) + Common.COMMA_TOKEN;
		if (currentIndex == numberOfChallenger) {
			MyLog.i("Choice: " + memoryChoice);
			if (memoryAnswer.equalsIgnoreCase(memoryChoice)) {
				numberOfPlay = 0;
				setResult(RESULT_OK);
				finish();
			} else {
				memoryText.setText("Remember the order");
				numberOfPlay++;
				currentIndex = 0;
				memoryChoice = "";
                Toast.makeText(MemoryActivity.this,getString(R.string.wrong_answer),Toast.LENGTH_SHORT);
				playGame();
			}
		}
	}

	private void Blink() {
		final Handler handler = new Handler();
		new Thread(new Runnable() {
			@Override
			public void run() {
				// int timeToBlink = 700; // in milissegunds
				try {
					Thread.sleep(timeToDelay);
				} catch (Exception e) {
					e.getStackTrace();
				}
				handler.post(new Runnable() {
					@Override
					public void run() {

						if (memoryText.getVisibility() == View.VISIBLE) {
							memoryText.setVisibility(View.INVISIBLE);
						} else {
							memoryText.setVisibility(View.VISIBLE);
						}
						Blink();
					}
				});
			}
		}).start();
	}
}
